package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.UserLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 下单或充值选择微信支付，返回小程序拉起微信支付所需参数
     * @param paymentType 支付类型：1301下单  1302充值
     * @param orderNo 订单/充值订单编号
     * @return {"timeStamp":"","package":"","paySign":"","signType":"RSA","nonceStr":""}
     */
    @UserLogin
    @Operation(summary = "下单或充值选择微信支付，返回小程序拉起微信支付所需参数")
    @PostMapping("/wxPay/createJsapi/{paymentType}/{orderNo}")
    public Result<Map<String, String>> createJsapi(@PathVariable("paymentType") String paymentType,
                                                   @PathVariable("orderNo") String orderNo){
        Map<String, String> map = wxPayService.createJsapi(paymentType,orderNo);
        return Result.ok(map);
    }

    /**
     * 查询订单支付状态
     * @param orderNo
     * @return
     */
    @UserLogin
    @Operation(summary = "支付订单查询")
    @GetMapping("/wxPay/queryPayStatus/{orderNo}")
    public Result<Boolean> queryPayStatus(@PathVariable("orderNo") String orderNo){
        boolean result = wxPayService.queryPayStatus(orderNo);
        return Result.ok(result);
    }

    /**
     * 提供给微信支付调用：用户微信付款成功后，微信通知商户支付结果
     *
     * @param request
     * @return
     */
    @Operation(summary = "微信支付成功后异步回调")
    @PostMapping("/wxPay/notify")
    public Result<Map<String,String>> wxPayNotify(HttpServletRequest request){
        Map<String,String> map = wxPayService.wxPayNotify(request);
        return Result.ok(map);
    }

    /**
     * 通过支付类型(订单or充值)和订单流水号获取本地交易记录 供订单服务中关闭第三方支付平台(微信支付)支付订单使用
     * @param paymentType
     * @param orderNo
     * @return
     */
    @Operation(summary = "通过订单流水号查询商家订单号")
    @PostMapping("/savePaymentInfo/{paymentType}/{orderNo}")
    public Result<PaymentInfo> getOutOrderNo(@PathVariable("paymentType") String paymentType,
                                                    @PathVariable("orderNo") String orderNo){
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);
        return Result.ok(paymentInfo);
    }


}
